import { defineStore } from "pinia"

const useStore = defineStore({
  id: "chats",
  persist: {
    enabled: true,
    key: 'LP_CHATS'
  },
  state: () => ({
    chats: [
      { aitype: null, messages: [] }
    ],
    index: 0,
  }),
  getters: {
    chat(state) {
      return state.chats[state.index]
    },
    messages(state) {
      return state.chats[state.index]?.messages || []
    }
  },
  actions: {
    aitypeToggle(type) {
      if (this.chats[this.index].aitype == type) {
        this.chats[this.index].aitype = null
        return
      }
      this.chats[this.index].aitype = type
    },
    addMessage(content) {
      this.chats[this.index].messages.push({ role: 'user', content })
      this.chats[this.index].messages.push({ role: 'assistant', content: '' })
    },
    newChat() {
      this.add()
      this.index = this.chats.length - 1
    },
    selectChat(d, i) {
      this.index = i
    },
    add(messages = []) {
      this.chats.push({
        aitype: null,
        messages
      })
    },
    clear() { // 清空会话
      this.chats = [{ aitype: null, messages: [] }]
      this.index = 0
    },

    del(d, i) {
      this.index = 0
      this.chats.splice(i, 1)
      if (!this.chats.length) {
        nextTick(() => {
          this.chats.push({ aitype: null, messages: [] })
        })
      }
    }
  }
})

export default useStore